<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BUIWXUser
 *
 * @author jianfeng
 */
class BUIUser extends BUIControl {

    //handle logic under this function
    const Render_Display_UserInfo = 'displayUserInfo';
    const Render_Modify_UserInfo = 'modifyUserInfo';
    const Render_Change_UserPassword = 'changeUserPassword';
    const Render_Apply_Member = 'applyForMember';
    const Render_Authenticate_User = 'displayAuthenticate';
    const Render_Authenticate_User_hamshun = 'displayAuthenticateHamshun';
    const Render_Authenticate_hamshun = 'authenticateHamshun';

    public function onRun($data = NULL) {
        parent::onRun($data);

        $theme = Blyn::app()->getUIManager()->getTheme();

        //$wxControl = new BUIWXControl('userInfo');
        //below code used for ajust theme control
        $control = new BUIControl('userInfo');
        if ($theme == BUIBlyn::Theme_Mobile_Bootstrap) {
            $control = new BUIWXControl('userInfo');
        }

        $sender = Blyn::app()->getUIManager()->getSenderControl();
        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();

        /*
          if ($sender->isAjaxLinkClicked(self::Render_Display_UserInfo)) {
          //$activeLink = Blyn::app()->getUIManager()->getActiveLink();
          //$updateControl->addRenderView(self::Render_Display_UserInfo);
          }
         * 
         */
        /*
          if ($sender->isAjaxLinkClicked(self::Render_Modify_UserInfo)) {
          $activeLink = Blyn::app()->getUIManager()->getActiveLink();
          $updateControl->addRenderView(self::Render_Modify_UserInfo);
          }
         * 
         */
        if ($sender->isAjaxLinkClicked(self::Render_Change_UserPassword)) {
            $activeLink = Blyn::app()->getUIManager()->getActiveLink();
            $updateControl->addRenderView(self::Render_Change_UserPassword);
        }
        /*
          if ($sender->isAjaxLinkClicked(self::Render_Apply_Member)) {
          $activeLink = Blyn::app()->getUIManager()->getActiveLink();
          $updateControl->addRenderView(self::Render_Apply_Member);
          }
         * 
         */
        if ($sender->isAjaxLinkClicked('saveUserInfo')) {
            $activeLink = Blyn::app()->getUIManager()->getActiveLink();
            $postManager = new BPostManager();
            $postData = $postManager->parsedModelData();
            $mediaList = $postManager->populateMediaListFromPostData($postData, 'userInfo');
            $user = Blyn::app()->getCurrentUser();
            $data = array();
            $userInfoTable = new BUserSheet('userInfo');
            $userInfoItem = $userInfoTable->getList(array('userId' => $user->getId()));

            $emailMedia = $mediaList['email'];
            if ($emailMedia) {
                unset($mediaList['email']);
                $data['email'] = $emailMedia->content;
                $userInfoItem->addItem('email', $data['email']);
                //$user->email = $emailMedia->content;
            }

            $userNameMedia = $mediaList['userName'];
            if ($userNameMedia) {
                unset($mediaList['userName']);
                $data['userName'] = $userNameMedia->content;
                $userInfoItem->addItem('userName', $data['userName']);
                //$user->userName = $userNameMedia->content;
            }

            $userIdMedia = $mediaList['userId'];
            if ($userIdMedia) {
                unset($mediaList['userId']);
                $data['userId'] = $userIdMedia->content;
                $userInfoItem->addItem('loginId', $data['userId']);
            }
            //$user->userId = $userIdMedia->content;
            $user->save($data);
            foreach ($mediaList as $key => $media) {
                $user->addAttribute('userInfo.' . $key, $media->content);
                $userInfoItem->addItem($key, $media->content);
            }

            $updateControl->addRenderView(self::Render_Display_UserInfo);
        }

        if ($sender->isAjaxLinkClicked('saveUserPassword')) {
            $user = Blyn::app()->getCurrentUser();
            $postManager = new BPostManager();
            $postData = $postManager->parsedModelData();
            $mediaList = $postManager->populateMediaListFromPostData($postData, 'userPassword');

            $oldPwd = $mediaList['password']->getContent();
            $newPwd = $mediaList['password1']->getContent();
            $confirmedPwd = $mediaList['password2']->getContent();

            $weChatAttr = $user->getAttribute('wxOpenId');
            if ($weChatAttr) {
                $openId = $weChatAttr->getValue();
                $oldPwd = $openId;
                $pwdAttr = $user->getAttribute('changedWechatPassword');
                if ($pwdAttr) {
                    $oldPwd = $pwdAttr->getValue();
                }
            }

            if ($newPwd == $confirmedPwd) {
                $attributes = array();
                $attributes['password'] = $newPwd;
                $isChangedPassword = $user->save($attributes);
//                $isChangedPassword = $user->changePassword($oldPwd, $newPwd);
            }

            if (isset($isChangedPassword) && $isChangedPassword) {
                $updateControl->addRenderView('changedPassword', self::Render_Change_UserPassword, array(
                    'isChangedPassword' => 'success'));
            } else {
                $updateControl->addRenderView(self::Render_Change_UserPassword, self::Render_Change_UserPassword, array(
                    'isChangedPassword' => 'fail'));
            }
        }
    }

    public function onDisplayUserInfo() {
        if (yii::app()->request->isAjaxRequest) {
            $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
            $updateControl->addRenderView(self::Render_Display_UserInfo);
        } else {
            /*
              $theme = Blyn::app()->getUIManager()->getTheme();
              $control = new BUIControl('userInfo');
              if ($theme == BUIBlyn::Theme_Mobile_Bootstrap) {
              $control = new BUIWXControl('userInfo');
              }
             * 
             */
            $control = new BUIThemedControl('userInfo');
            $activeLink = Blyn::app()->getUIManager()->getActiveLink();
            $this->addChildControl($control);
            $control->addRenderView(self::Render_Display_UserInfo);
        }
    }

    public function onModifyUserInfo($data = NULL) {
        if (yii::app()->request->isAjaxRequest) {
            $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
            $updateControl->addRenderView(self::Render_Modify_UserInfo);
        } else {
            $control = new BUIThemedControl('modifyUserInfo');
            //$activeLink = Blyn::app()->getUIManager()->getActiveLink();
            $this->addChildControl($control);
            $control->addRenderView(self::Render_Modify_UserInfo);
        }
    }

    public function onDisplayAuthenticate($data = NULL) {
        if (yii::app()->request->isAjaxRequest) {
            $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
            $updateControl->addRenderView(self::Render_Authenticate_User);
        } else {
            $control = new BUIThemedControl('userAuthenticate');
            //$activeLink = Blyn::app()->getUIManager()->getActiveLink();
            $this->addChildControl($control);
            $control->addRenderView(self::Render_Authenticate_User);
        }
    }
    
    public function onDisplayAuthenticateHamshun($data = NULL) {
        if (yii::app()->request->isAjaxRequest) {
            $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
            $updateControl->addRenderView(self::Render_Authenticate_User);
        } else {
            $control = new BUIThemedControl('userAuthenticate');
            //$activeLink = Blyn::app()->getUIManager()->getActiveLink();
            $this->addChildControl($control);
            $control->addRenderView(self::Render_Authenticate_User_hamshun);
        }
    }
    public function onAuthenticateHamshun() {
        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        $user = Blyn::app()->getCurrentUser();
        $userInfo = $user->getAttribute('userInfo');
        $isAuthenticateHamshun = 'no';
        $attributes = array();
        if ($userInfo) {
            $attributes = $userInfo->getChildren();
                foreach ($attributes as $attr) {
                    if($attr->getName() == 'isAuthenticateHamshun'){
                        $isAuthenticateHamshun = $attr->getValue();  
                    }
             }
        }
        if($isAuthenticateHamshun == 'yes'){
            $updateControl->addRenderView('displayUserInfo_hamshun');
        }  else {
            $updateControl->addRenderView(self::Render_Authenticate_User_hamshun);
        } 
    }
    public function onAuthenticateUser($data = NULL) {
        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        $postManager = new BPostManager();
        $postData = $postManager->parsedModelData();
        $mediaList = $postManager->populateMediaListFromPostData($postData, 'userInfo');
        $user = Blyn::app()->getCurrentUser();
        $data = array();
        //采集信息
        $name = $mediaList['userName']->content;
        $phone = $mediaList['mobile']->content;
        $teacherno = $mediaList['teacherNo']->content;
        $openid = $mediaList['openid']->content;

        //验证
        $identyData = '{"name":' . $name . ',"phone":' . $phone . ',"teacherno":' . $teacherno . ',' . '"openid":' . $openid . '}';
        $url = 'http://210.209.93.90:8093/Message/weChatIdenty?identystr=' . $identyData;
        $weixin = new BWeChatClass("wxdfdd543f3624de1a", "0d263ad0ccbd55da5f61b105ffd90ef8");
        $res_arr = (json_decode($weixin->https_request($url), true));
        if ($res_arr["result"] == "1") {
            //与后台验证成功
            $message = '尊敬的用户，您已经成功认证个人信息！感谢您的配合。';
            $type = 'text';
            $send_err = $weixin->send_custom_message($openid, $type, $message);
            $send_res = json_decode($send_err, true);
            if ($send_res["errmsg"] == "ok") {
                //发送消息成功
                $userNameMedia = $mediaList['userName'];
                unset($mediaList['userName']);
                $data['userName'] = $userNameMedia->content;

                $user->save($data);
                foreach ($mediaList as $key => $media) {
                    $user->addAttribute('userInfo.' . $key, $media->content);
                }
                $updateControl->addRenderView('afterAuthenticate');
            }
        }
    }
    public function onAuthenticateUserHamshun($data = NULL) {
        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        $postManager = new BPostManager();
        $postData = $postManager->parsedModelData();
        $mediaList = $postManager->populateMediaListFromPostData($postData, 'userInfo');
        $user = Blyn::app()->getCurrentUser();
        $data = array();
        //采集信息
        $name = $mediaList['userName']->content;
        $useridcard = $mediaList['useridcard']->content;
        $openid = $mediaList['openid']->content;
//        $openid="oxmO-uNBCGBjzWouLnH44JrmutiA";

        //验证
        $url = "http://210.209.93.90:8012/WechatAuthentication/WechatAuthenticationx?username=". $name ."&useridcard=".$useridcard;
        $weixin = new BWeChatClass("wxd33a8d04590d6e58", "de068491fd6a4f42f122c7d2f10208b2");
        $res = $weixin->https_request($url);
//        $res = "success,周廷勇,13896724130,512323197902140091,6228480470661827712";
        if ($res != "false") {
            //与后台验证成功
            $message = '尊敬的用户，您已经成功认证个人信息！感谢您的配合。';
            $type = 'text';
            $send_err = $weixin->send_custom_message($openid, $type, $message);
            $send_res = json_decode($send_err, true);
            if ($send_res["errmsg"] == "ok") {
                //发送消息成功
                $userNameMedia = $mediaList['userName'];
                unset($mediaList['userName']);
                $data['userName'] = $userNameMedia->content;

                $user->save($data);
                foreach ($mediaList as $key => $media) {
                    $user->addAttribute('userInfo.' . $key, $media->content);
                }
                $return_arr = explode(',', $res);
                $user->addAttribute('userInfo.mobile', $return_arr[2]);
                $user->addAttribute('userInfo.bankNum', $return_arr[4]);
                $updateControl->addRenderView('displayUserInfo_hamshun');
            }
        }
//        $userNameMedia = $mediaList['userName'];
//        unset($mediaList['userName']);
//        $data['userName'] = $userNameMedia->content;
//
//        $user->save($data);
//        foreach ($mediaList as $key => $media) {
//            $user->addAttribute('userInfo.' . $key, $media->content);
//        }
//        $updateControl->addRenderView('displayUserInfo_hamshun');
    }
    public function onSendWechatMessage($data = NULL) {
        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        $updateControl->addRenderView('sendWechatMessage', 'sendWechatMessage', array('result' => 'send out successfully!'));
    }

    public function onShowSendWechatMessage($data = NULL) {
        if (isset($_GET)) {
            $openid = $_GET['openid'];
            $message = $_GET['message'];
            $type = 'text';
            $weixin = new BWeChatClass("wxdfdd543f3624de1a", "0d263ad0ccbd55da5f61b105ffd90ef8");
            $send_err = $weixin->send_custom_message($openid, $type, $message);
            $send_res = json_decode($send_err, true);
            if ($send_res["errmsg"] == "ok") {
                //发送消息成功
                //$msg = array('result'=>'1','message'=>'success');
                //$url='';
                //return $weixin->https_request($url, urldecode(json_encode($msg)));
                return 'success';
            }
        }
//        if (yii::app()->request->isAjaxRequest) {
//            $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
//            $updateControl->addRenderView(self::Render_Authenticate_User);
//        } else {
//            $control = new BUIThemedControl('sendWechatMessage');
//            //$activeLink = Blyn::app()->getUIManager()->getActiveLink();
//            $this->addChildControl($control);
//            $control->addRenderView('sendWechatMessage');
//        }
    }

}
